﻿var addcontactGrid = addcontactGrid || {};
var isGridLoadFirstime = true;

var uid;
var lastRequest;


function onRequestEnd(e) {
    debugger;
    lastRequest = e.type;
}

function onSync(e) {
    debugger;
    if (lastRequest !== "destroy") {
        $("#addcontactGrid table").find("tr[data-uid='" + uid + "']").addClass("k-state-selected");

        //$('#addcontactGrid tr.k-state-selected').removeClass('k-state-selected');
        //var row = $(e).closest("tr");
        //row.addClass("k-state-selected");
    }
}
function onSave(e) {
    uid = e.container.attr("data-uid");
}



addcontactGrid = function () {
    var gridInEditMode = false;
    var addcontactDropDownChanged = false;
 
   
  
    var addcontactDataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/AddContact/GetAddContacts",
                type: "get",
                     cache: false,
                dataType: "json",
             
            },
            create: {
                url: "/AddContact/CreateAddContact",
                type: 'POST',
                dataType: "json",
                contentType: "application/JSON"

            },
            update: {
                url: "/AddContact/UpdateAddContact",
                type: 'POST',
                dataType: "json",
                contentType: "application/JSON"
            },
            destroy: {
                url: "/AddContact/DeleteAddContact",
                type: "POST",
                dataType: "json",
                contentType: "application/JSON"
            },
            parameterMap: function (options) {
                return kendo.stringify(options); // kendo.stringify serializes to JSON string
            }
        },

        pageSize: 10,
        schema: {
            model: {
                id: "id",
                fields: {
                    id: {
                        editable: false, nullable: true,
                        type: "int"
                    },
                    name: {
                        type: "string",
                        hidden: true,
                        editable: false
                    },

                    firstName: {
                        type: "string",
                        hidden: true,

                    },
                    lastName: {
                        type: "string",
                        hidden: true
                    },
                    userId:
                        {
                            type:"int",
                             defaultValue: 0
                        },
                   
                    startDate: {
                        type: "date",
                        editable: false
                    },
                  
                    error: function (a) {
                        $('#addcontactGrid').data("kendoGrid").cancelChanges();
                    },
                 
                }
            }
        },
        requestEnd: onRequestEnd,
        sync: onSync

    });

    var company = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/ScratchPad/GetJustCompanyName/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });
    var contactDetails = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/ScratchPad/GetContactDetail/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        },
        requestEnd: function (a, b) {

        }

    });

    var contantType = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/AddContact/GetContactTypes/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });
    var jobTitle = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/AddContact/GetJobTitles/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });

    var department = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/AddContact/GetDepartments/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });
   

    return {
        addcontactDataSource: addcontactDataSource,
        company: company,
        contactDetails: contactDetails,
        contantType: contantType,
        jobTitle: jobTitle,
        department: department,
       
       
        addcontactDropDownChanged: addcontactDropDownChanged,
        gridInEditMode: gridInEditMode


    }

}();

$(function () {
  

 
    function dateTimeEditor(container, options) {
        $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
        .appendTo(container)
        .kendoDateTimePicker({});
    }
    var origKeys = [];
   $("#addcontactGrid").kendoGrid({
        dataSource: addcontactGrid.addcontactDataSource,
        dataBound: function (e) {
            debugger;
         
         
            if (isGridLoadFirstime == true) {
                isGridLoadFirstime = false;
                var count = 0; var IsItemFound = false;
                var dataList = e.sender.dataSource.data()
                for (var i = 0; i < dataList.length; i++) {
                    var list = dataList[i];
                    count++;
                    if (list.firstName == window.location.hash.substr(1).split(',')[1] &&
                        list.lastName == window.location.hash.substr(1).split(',')[0]) {
                        IsItemFound = true;
                        break;
                    }
                }

                if (IsItemFound == true) {
                    var pagesize = e.sender.dataSource.pageSize();
                    var currentpage = parseInt(count / pagesize) + 1;
                    e.sender.dataSource.page(currentpage);
                }

            }

            var rows = e.sender.tbody.children();

            for (var j = 0; j < rows.length; j++) {

                var row = $(rows[j]);
                var dataItem = e.sender.dataItem(row);
               

                if (dataItem.get("firstName") == window.location.hash.substr(1).split(',')[1] && dataItem.get("lastName") == window.location.hash.substr(1).split(',')[0]) {
                    row.addClass("someCssColorClass");
                }
            }

            //var grid = this;
            //// get current keys
            //var keys = $.map(addcontactGrid.addcontactDataSource.view(), function (item) {
            //    return item.id;
            //});

            //var newkeys = $.grep(keys, function (item) {
            //    return $.inArray(item, origKeys) == -1;
            //});

            //$.each(newkeys, function (idx, key) {
            //    var uid = addcontactGrid.addcontactDataSource.get(key).uid;
            //    grid.tbody.find("[data-uid=" + uid + "]").css("background-color", "yellow");
            //});

            //origKeys = keys;
        },

        scrollable: true,
        height: "250px",
        toolbar: [{ name: "create", text: "Add a Contact" }, "excel"], //, "save", "cancel"],
        excel: {
            fileName: "ContactsExport.xlsx"
        },
        pageable: true,
        height: 500,
        columns: [

        { field: "details", title: "Details", filterable: false, width: "6em", template: "<a onclick=\"showDetails('#=id #', this);\"style=\"cursor: pointer;\"> View</a>" },
          { field: "company", title: "Company", filterable: false, width: "6em", template: "<a onclick=\"showCompany('#=id #' , this);\"style=\"cursor: pointer;\"> View</a>" },
          { field: "MSg", title: "MSG", filterable: false, width: "6em", template: "<a onclick=\"showCompanyMessages('#=id #', this);\"style=\"cursor: pointer;\"> View</a>" },
      { field: "name", title: "FullName", width: "10em", filterable: true },
      
       { field: "firstName", title: "First Name", width: "10em", hidden: true, editable: true, filterable: false },
        { field: "lastName", title: "Last Name", width: "10em", hidden: true, editable: true, filterable: false },

    {
        field: "startDate", title: "Start Date", width: "10em", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
        editor: dateTimeEditor,
        filterable: {
            ui: "datetimepicker"
        }
    },
      {
          title: "&nbsp;",
          width: "12em",
          // command: ["edit", "destroy"]
          command: [

              "edit",
              {
                  name: "Delete",


                  click: function (e) {

                      var tr = $(e.target).closest("tr"); //get the row for deletion
                      var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                      //see what is coming in dataItem
                      //if (dataItem.QuestionAnswers.length > 0) {
                      //    $("#delValidation").addClass('in')
                      //}
                      //else {

                      deleteTopicConfirmation(e, this);
                      // }
                      return false;
                  }
              }
          ]
      }
        ],
        filterable: {
            extra: false,
            operators: {
                string: {
                    eq: "Is equal to",
                    neq: "Is not equal to",
                    contains: "Contains"
                }
            }
        },

        editable: "popup",
        sortable: {
            mode: "single",
            allowUnsort: false
        },
        selectable: true,

        edit: function (e) {
            e.container.find(".k-edit-label:nth-child(1)").hide();
            e.container.find(".k-edit-field:nth-child(2)").hide();
            e.container.find(".k-edit-label:nth-child(3)").hide();
            e.container.find(".k-edit-field:nth-child(4)").hide();
            e.container.find(".k-edit-label:nth-child(5)").hide();
            e.container.find(".k-edit-field:nth-child(6)").hide();
            e.container.find(".k-edit-label:nth-child(7)").hide();
            e.container.find(".k-edit-field:nth-child(8)").hide();
            // e.container.find(".k-edit-label:nth-child(9)").hide();

            // e.container.find(".k-edit-field:nth-child(9)").hide();



            addcontactGrid.gridInEditMode = true;
        },
        save: function (e) {
            alert(1);
            uid = e.container.attr("data-uid");
        },

        cancel: function () {
            addcontactGrid.gridInEditMode = false;
        }
  });

    
   
   


   //function saveContacts(e) {
   //    debugger;
   //    var grid = $("#addcontactGrid").data("kendoGrid");
   //    var dataItem = grid.dataSource.get(e.model.id);
   //      var row = grid.tbody.find("tr[data-uid='" + dataItem.uid + "']");
       
   //       grid.select(row);
   //    }

    addcontactGrid.addcontactDataSource.bind("requestEnd", showSuccessMessage);
    function showSuccessMessage(e) {
        if (e.type === "update" || e.type === "create") {
            addcontactGrid.gridInEditMode = false;
            $("#saveConfirm").addClass('in');
            e.sender.read();
        }
    }
    $(".close").click(function () {
        $(this).parent().removeClass('in');
    });
    function deleteTopicConfirmation(e, widget) {
        var grid = $('#addcontactGrid').data("kendoGrid");
        deleteConfirmation(e, widget, grid);
    }

    function deleteConfirmation(e, widget, grid) {

        var currentRow = $(e.target).closest("tr"); //get the row for deletion

        var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

        var kendoWindow = $("<div />").kendoWindow({

            title: "Confirmation",
            resizable: true,
            modal: true,
            width: "400px"
        });

        kendoWindow.data("kendoWindow")

            .content($("#delete-confirmation").html())

            .center().open();

        kendoWindow

            .find(".delete-confirm,.delete-cancel")
            .click(function () {
                if ($(this).hasClass("delete-confirm")) {

                    grid.dataSource.remove(currentRowData);

                    grid.dataSource.sync();

                }

                $(this).closest("[data-role=window]").kendoWindow("close");

            });

    }
    function companyDropDownEditor(container, options) {

        $('<input data-text-field="cpName" data-value-field="cpName" data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataSource: addcontactGrid.company

        });
    }
    function contactTypeDropDownEditor(container, options) {

        $('<input data-text-field="description" data-value-field="description"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataSource: addcontactGrid.contantType
        });
    }
    function jobTitleDropDownEditor(container, options) {

        $('<input data-text-field="code" data-value-field="code"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataSource: addcontactGrid.jobTitle

        });
    }
    function departmentDropDownEditor(container, options) {

        $('<input data-text-field="departmentCode" data-value-field="departmentCode"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataSource:
                addcontactGrid.department

        });
    }

   
    function contactAutoCompleteEditor(container, options) {
        $('<input data-text-field="name"  data-value-field="Name"  data-bind="value:' + options.field + '"/>')
        .appendTo(container)
        .kendoAutoComplete({
            autoBind: true,
            suggest: true,
            placeHolder: "enter caller name here",
            filter: "contains",
            //   index: 1,
            minLength: 1,
            dataSource: addcontactGrid.contactDetails
        });
    }


});


